package com.demo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import jersey.repackaged.com.google.common.collect.Maps;

import com.alibaba.fastjson.JSON;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

/**
 * @Description 科界http调用
 * @Author shiyuhao
 * @Email shi.yuhao@scimall.org.cn
 * @Date 2020/9/23 10:32 上午
 **/
public class HttpClient {

    public static String invoke(String url, String appId, String secretKey, Map<String, Object> param) {
        StringBuilder singleParam = new StringBuilder(url + "?");
        try {
            handleSignParam(appId, secretKey, url, singleParam, param);
        } catch (MalformedURLException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", HttpStatus.HTTP_BAD_GATEWAY);
            error.put("msg", "invalid url");
            return JSON.toJSONString(error);
        }
        return HttpUtil.post(singleParam.toString(), param);
    }

    private static void handleSignParam(String appId, String secretKey, String url, StringBuilder signParam, Map<String, Object> param) throws MalformedURLException {
        URL temp = new URL(url);
        String path = temp.getPath();

        Long timestamp = DateUtil.currentSeconds();
        param.put("timestamp", timestamp + "");
        param.put("appid", appId);
        param.put("path", path);

        signParam.append("appid=").append(appId);
        signParam.append("&timestamp=").append(timestamp);
        signParam.append("&path=").append(path);
        signParam.append("&sn=").append(buildSn(appId, secretKey, param));
    }

    public static String buildSn(String appId, String secretKey, Map<String, Object> params) {
        Map<String, Object> sortedMap = Maps.newTreeMap(String::compareTo);
        if (params != null) {
            params.remove("secretkey");
            params.remove("appid");
            sortedMap.putAll(params);
        }

        sortedMap.put("appid", appId);

        StringBuilder sn = new StringBuilder();
        sortedMap.forEach((k, v) -> {
            sn.append("&");
            sn.append(k);
            sn.append("=");
            sn.append(v);
        });

        sn.append("&secretkey=").append(secretKey);
        sn.deleteCharAt(0);

        return md5Hex(md5Hex(sn.toString().toLowerCase())).toLowerCase();
    }

    
	/**
	 * SSO拉取用户信息
	 * @param url 
	 * @param appId 
	 * @param secretKey
	 * @param sign sso认证中心返回的sign
	 * @param token sso 认证中心返回的token
	 * @return
	 */
	public static String getUserInfo(String url, String appId,String secretKey,String sign,String token) {
		Map<String, Object> param = new HashMap<>();
	        param.put("sso_sign", sign);
	        param.put("sso_token", token);
	    return HttpClient.invoke(url+="/sso/getuserinfo", appId, secretKey, param);
	}
	
	
}
